<?php

/**
 * Created with IntelliJ IDEA.
 * @Auther: 张昶
 * @Date: 2020/05/06/11:41
 * @Description:
 */

namespace app\api\controller;


use think\Controller;
use think\Db;
use think\Request;

class Chat extends Controller
{

    /**
     *文本消息的数据持久化
     *
    * @Description
    * @Date   2020/5/6 11:44
    */
    public function save_message()
    {
            $message = input("post.");
            $data['fromid'] = $message['fromid'];
            $data['fromname'] = $this->getName($data['fromid']);
            $data['toid'] = $message['toid'];
            $data['toname'] = $this->getName($data['toid']);
            $data['content'] = $message['data'];
            $data['time'] = $message['time'];
//            $data['isread'] = $message['isread'];
            $data['isread'] = 0;
            $data['type'] = 1;
            Db::name("communication")->insert($data);
    }

    /**
     * 根据用户id返回用户的姓名
    * @Description
    * @Date   2020/5/6 16:15
    */
    public function getName($uid)
    {
        $userinfo = Db::name("user")->where('id',$uid)->field('nickname')->find();
        return $userinfo['nickname'];
    }


    /**根据用户id获取聊天双方的,获取用户的头像
    * @Description
    * @Date   2020/5/6 17:30
    */
    public function get_head()
    {
        $fromid = input('fromid');
        $toid = input('toid');

       $frominfo =  Db::name('user')->where('id', $fromid)->field('headimgurl')->find();

        $toinfo =  Db::name('user')->where('id', $toid)->field('headimgurl')->find();

        return [
            'from_head'=>$frominfo['headimgurl'],
            'to_head'=>$toinfo['headimgurl']
        ];
    }
    
    
    //获取单个用户头像名称 (根据用户id返回用户名称)
    public function get_name()
    {
        if (Request::instance()->isAjax()){
            $uid = input('uid');
            $toinfo = Db::name('user')->where('id',$uid)->field('nickname')->find();

            return [
                "toname"=>$toinfo['nickname'],
            ];
        }
    }

    //页面加载返回聊天记录
    public function load()
    {
        if (Request::instance()->isAjax()){

            $fromid = input('fromid');
            $toid   = input('toid');

           $count =  Db::name('communication')->where('(fromid=:fromid and toid=:toid) || (fromid=:toid1 and toid=:fromid1)', ['fromid'=>$fromid,'toid'=>$toid,'toid1'=>$toid,'fromid1'=>$fromid])->count('id');
           if ($count>=10){
               $message =  Db::name('communication')->where('(fromid=:fromid and toid=:toid) || (fromid=:toid1 and toid=:fromid1)', ['fromid'=>$fromid,'toid'=>$toid,'toid1'=>$toid,'fromid1'=>$fromid])->limit($count-10,10)->order('id')->select();

           }else{
               $message =  Db::name('communication')->where('(fromid=:fromid and toid=:toid) || (fromid=:toid1 and toid=:fromid1)', ['fromid'=>$fromid,'toid'=>$toid,'toid1'=>$toid,'fromid1'=>$fromid])->order('id')->select();
           }
            return $message;
        }
    }


    //获取上传文件的操作  (上传图片，返回图片的地址)
    public function uploadimg()
    {
        $file = $_FILES['file'];
        $fromid = input('fromid');
        $toid = input('toid');
        $online = input('online');

        $suffix = strtolower(strrchr($file['name'],'.'));//截取后缀名
        $type = ['.jpg','.jpeg','.gif','.png',]; //图片需要的类型（判断使用）
        if (!in_array($suffix,$type)){
            return ['status'=>'文件上传错误！'];
        }
        if ($file['size']/1024>5120){
            return ['status'=>'w文件大小超过范围！'];
        }

        $filename = uniqid("chat_img_",false); //上传图片的名称
        $uploadpath = ROOT_PATH.'public\\uploads\\'; //上传文件的保存地址
        $file_up = $uploadpath.$filename.$suffix; //上传文件的的操作

        $re = move_uploaded_file($file['tmp_name'],$file_up); //移动到上传的地址
        if ($re){
            $name = $filename.$suffix;
            $data['content'] = $name;
            $data['fromid'] =$fromid;
            $data['toid'] =$toid;
            $data['fromname'] =$this->getName($data['fromid']) ;
            $data['toname'] =$this->getName($data['toid']) ;
            $data['time'] =time();
//            $data['isread'] =$online;
            $data['isread'] = 0;
            $data['type'] =2; //文本消息默认为1，图片消息默认为2

            $message_id = Db::name('communication')->insertGetId($data);
            if ($message_id){
                return ['status'=>'ok','img_name'=>$name];
            }else{
                return ['status'=>'false'];
            }
        }
    }



    /**
     * 根据uid来获取它的头像
    * @Description
    * @Date   2020/5/8 15:51
    */
    public function get_head_one($uid)
    {
        $fromhead = Db::name('user')->where('id',$uid)->field('headimgurl')->find();
        return $fromhead['headimgurl'];
    }

    /**
     * 获取未读消息的数量 （fromid发送给toid的未读的数量）
    * @Description
    * @Date   2020/5/8 15:58
    */
    public function getCountNoread($fromid,$toid)
    {
        return Db::name('communication')->where(['fromid'=>$fromid,'toid'=>$toid,'isread'=>0])->count('id');
    }
    
    /**
     * 获取聊天的最后一条数据
    * @Description
    * @Date   2020/5/8 16:04
    */
    public function getLastMessage($fromid,$toid)
    {
        $info = Db::name('communication')->where('(fromid=:fromid&&toid=:toid) ||(fromid=:fromid2&&toid=:toid2)',['fromid'=>$fromid,'toid'=>$toid,'fromid2'=>$toid,'toid2'=>$fromid])->order('id DESC')->limit(1)->find(); //获取最后一条的数据
          return $info;
    }






    //获取聊天的列表
    public function get_list()
    {
        if (Request::instance()->isAjax()){

            $fromid = input('id');
            $info = Db::name('communication')->field(['fromid','toid','fromname'])->where('toid',$fromid)->group('fromid')->select();

            //循环数组
           $rows =   array_map(function ($res){
                return [
                    'head_url'=>$this->get_head_one($res['fromid']),    //获取头像（对方的）
                    'username' => $res['fromname'],
                    'countNoread'=>$this->getCountNoread($res['fromid'],$res['toid']),  //获取未读的信息的数量
                    'last_message'=>$this->getLastMessage($res['fromid'],$res['toid']),   //获取聊天数据
                    'chat_page'=>"http://www.chat.com/index.php/index/index/index?fromid={$res['toid']}&toid={$res['fromid']}"  //信息来自哪里，给谁看的信息
                ];

            }, (array)$info);
           
            return $rows;
        }
    }

    //改变未读消息的状态
    public function changeNoRead()
    {
        if (Request::instance()->isAjax()){
            $fromid = input('toid');
            $toid = input('fromid');
            Db::name('communication')->where(['fromid'=>$fromid,'toid'=>$toid])->update(['isread'=>1]);

        }


    }

}